<?php
/**
 *
 * 权限验证类
 */
/*
DROP TABLE IF EXISTS `mycms_auth_rule`;
CREATE TABLE `mycms_auth_rule` (  
    `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,  
    `name` char(80) NOT NULL DEFAULT '',  
    `title` char(20) NOT NULL DEFAULT '',  
    `status` tinyint(1) NOT NULL DEFAULT '1',  
    `condition` char(100) NOT NULL DEFAULT '',  
    PRIMARY KEY (`id`),  
    UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `mycms_auth_group`;
CREATE TABLE `mycms_auth_group` ( 
    `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, 
    `title` char(100) NOT NULL DEFAULT '', 
    `status` tinyint(1) NOT NULL DEFAULT '1', 
    `rules` char(80) NOT NULL DEFAULT '', 
    PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `mycms_auth_group_access`;
CREATE TABLE `mycms_auth_group_access` (  
    `uid` mediumint(8) unsigned NOT NULL,  
    `gid` mediumint(8) unsigned NOT NULL, 
    UNIQUE KEY `uid_group_id` (`uid`,`gid`),  
    KEY `uid` (`uid`), 
    KEY `gid` (`gid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/

Class Auth {
	protected $_config = array(
		'AUTH_ON'           => 1,
		'AUTH_TYPE'         => 1,
		'AUTH_GROUP'        => 'auth_group',
		'AUTH_RULE'         => 'auth_rule',
		'AUTH_GROUP_ACCESS' => 'auth_group_access',
		'AUTH_USER'         => 'usercenter'
	);
	/**
	 * 构造函数
	 */
	public function __construct() {
		//加上表前缀
		$dbPrefix                           = C('DB_PREFIX');
		$this->_config['AUTH_GROUP']        = $dbPrefix.$this->_config['AUTH_GROUP'];
		$this->_config['AUTH_RULE']         = $dbPrefix.$this->_config['AUTH_RULE'];
		$this->_config['AUTH_USER']         = $dbPrefix.$this->_config['AUTH_USER'];
		$this->_config['AUTH_GROUP_ACCESS'] = $dbPrefix.$this->_config['AUTH_GROUP_ACCESS'];

		//合并配置文件
		if(C('AUTH_CONFIG')) {
			$this->_config = array_merge($this->_config , C('AUTH_CONFIG'));
		}
	}

	/**
	 * 权限验证
	 * @param  [type]  $name     [description]
	 * @param  [type]  $uid      [description]
	 * @param  integer $type     [description]
	 * @param  string  $mode     [description]
	 * @param  string  $relation [description]
	 * @return [type]            [description]
	 */
	public function check($name , $uid,  $type = 1, $mode = 'url', $relation = 'or') {
		//判断权限验证开关
		if(!$this->_config['AUTH_ON']) {
			return false;
		}
		//获取用户权限列表
		$authList = $this->getAuthList($uid);
		//处理验证参数
		if(is_string($name)) {
			$name = strtolower($name);
			if( false !== strpos($name, ',')) {
				$rules = explode(',', $name);
			}else{
				$rules = array($name);
			}
		}
		$authRules = array();
		//循环判断规则 实验检测效率
		foreach ($authList as $a) {
			if(in_array($a, $rules)) {
				$authRules[] = $a;
			}
		}
		//or条件
		if($relation == 'or' && !empty($authRules)) {
			return true;
		}
		//and条件
		$diff = array_diff($rules , $authRules);
		if($relation == 'and' && empty($diff)) {
			return true;
		}
		return false;
	}

	/**
	 * 获取用户权限规则列表
	 * @param  [type] $uid [description]
	 * @return [type]      [description]
	 */
	public function getAuthList($uid) {

		static $_authList = array();
		//1.判断用户权限列表是否存在
		if(isset($_authList[$uid])) {

			return $_authList[$uid];
		}
		//2.用户权限列表SESSION是否存在
		if(isset($_SESSION['_AUTH_LIST_' . $uid])) {
			return $_SESSION['_AUTH_LIST_'.$uid];
		}

		//3.获取用户权限所属权限组的规则
		$groups = $this->getGroups($uid);
		$rid    = array();
		foreach ($groups as $g) {
			$rid = array_merge($rid , explode(',' , trim($g['rules'])));
		}
		//去重
		$rid = array_unique($rid);
		//容错
		if(empty($rid)) {
			return $_authList[$uid] = array();
		}
		//查询参数
		$map = array(
			'id'     => array('in',$rid),
			'status' => 1,
		);
		//5.获取当前用户对应的权限规则
		$rules = M()->table($this->_config['AUTH_RULE'])->where($map)->select();

		$authList = array();
		//6.循环判断规则有效
		foreach ($rules as $r) {
			if(!empty($condition)) {
				//1.
			}else{
				$authList = array($r['name']);
			}
		}

		$_authList[$uid] = $authList;

		if($this->_config['AUTH_TYPE'] == 2){
            //session结果
            $_SESSION['_AUTH_LIST_'.$uid] = $authList;
        }

        return $authList;
	}

	/**
	 * [getGroups description]
	 * @param  [type] $uid [description]
	 * @return [type]      [description]
	 */
	public function getGroups($uid) {
		static $groups = array();
		if(isset($groups[$uid])) {
			return $groups;
		}
		$user_groups = M()->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')
		   				  ->where("a.uid = $uid and g.status = '1' ")
		   				  ->join($this->_config['AUTH_GROUP'] . ' g on a.gid = g.id')
		   				  ->field('rules')
		   				  ->select();
	  	$groups[$uid] =  $user_groups ? $user_groups : array();
	  	return $groups[$uid];
	}

	/**
	 * [getUserInfo description]
	 * @param  [type] $uid [description]
	 * @return [type]      [description]
	 */
	public function getUserInfo($uid) {

	}

}